package com.bluedon.ism.commons.action;

import com.bluedon.ism.commons.entity.OperateAuth;
import com.bluedon.ism.commons.entity.Permission;
import com.bluedon.ism.commons.entity.Role;
import com.bluedon.ism.commons.operationlog.aspect.OperateLogAnnotation;
import com.bluedon.ism.commons.service.OrganizationService;
import com.bluedon.ism.commons.service.RBACService;
import com.bluedon.ism.commons.shiro.RBACConstants;
import com.bluedon.ism.commons.util.BeanUtil;
import com.bluedon.ism.commons.util.Constants;
import com.bluedon.ism.commons.util.StringUtil;
import com.bluedon.ism.commons.util.WriteUtil;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.bluedon.ism.commons.operationlog.LogConstantAdmin.*;

public class RoleAction extends BaseAdminAction {

    @Resource(name = "organizationService")
    private OrganizationService organizationService;
    @Resource(name="accountRBACService")
    private RBACService accountRBACService;
    

    private Role role;
    private OperateAuth oauth;

    /**
     * 查看用户角色列表
     * @return
     */
    @OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_FINDALLPCROLE,
    		message=MG_ROLE_FINDALLPCROLE_MSG)
	public String findAllPcRole() {  
	    setOrgSelectBoxInRequest();
		String orgId = request.getParameter("orgId") == null ? getSessionOrgId() : request.getParameter("orgId");
		String keywork1 = StringUtil.trimToEmpty(request.getParameter("keywork1"));
		request.setAttribute("orgId", orgId); 
		request.setAttribute("keywork1", keywork1);
		String export = StringUtil.trimToEmpty(request.getParameter("export"));
		if("yes".equals(StringUtil.trimToEmpty(export))){
			response.setHeader("Content-disposition", "attachment;filename=AllPcRole.xls");
			List<Role> list = this.accountRBACService.getAllPcRole(-1, -1,keywork1, orgId).getList();
			request.setAttribute("list", list);
			return "download";
		}else{
			pager = this.accountRBACService.getAllPcRole(pager.getPageNo(), pager.getPageSize(),keywork1, orgId);
			return SUCCESS;
		}
	}
	
	/**
	 * 增加角色
	 */
	@Transactional()
    @OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_ADDPCROLE,
    		message=MG_ROLE_ADDPCROLE_MSG,
    		httpMethod="POST")
	public String addPcRole() {
	    
       if(isGet()){
           request.setAttribute("districtList", getAccountService().getFuzzyDistrictByDid(getSessionOrgId()));
           return INPUT;
       }
       if(isPost()) {
        if (!BeanUtil.checkProperties(Role.class, role, new String[]{"roleName", "organization", "createUser"}))
            return INPUT;
        
		role.setCreateTime(new Date());
		role.setIsSystem(false);
		accountRBACService.addRole(role);
		
		request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "成功添加角色");
		return SUCCESS;
       }
       
       return INPUT;
	}
	
	/**
	 * goto账号角色授权
	 */
	@Transactional
	 @OperateLogAnnotation(
	    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
	    		operateTypeName=MG_ROLE_GOTOPERMROLE,
	    		message=MG_ROLE_GOTOPERMROLE_MSG)
	public String goToPermRole() {
		Long rid = Long.valueOf(StringUtil.trimToEmpty(request.getParameter("rid")));
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"url"});
		role = accountRBACService.findRoleById(rid);
		request.setAttribute("menTree", 
		        JSONArray.fromObject(accountRBACService.getPcPermissionTreeOfRole(role.getOrganization().getOid(), rid, true, false)
		                ,config).toString());
		request.setAttribute("rid", rid);
		return SUCCESS;
	}
	
	/**
	 * goto分配用户角色
	 */
	@Transactional() 
	public String goToAssginRole() {
		String username = StringUtil.trimToEmpty(request.getParameter("username"));
		Long aid =  Long.valueOf(StringUtil.trimToEmpty(request.getParameter("aid")));
		String oid = StringUtil.trimToEmpty(request.getParameter("oid"));
		request.setAttribute("roleList", accountRBACService.getAssginRoleByOrgId(aid, oid));
		request.setAttribute("aid", aid);
		request.setAttribute("username", username);
		return SUCCESS;
	}

	/**
	 * 分配用户 角色
	 */
	@Transactional() 
	@OperateLogAnnotation(
			moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,
			operateTypeName=MG_ACCOUNT_MANAGER_DOASSGINROLE,
			message=MG_ACCOUNT_MANAGER_DOASSGINROLE_MSG
			)
	public String doAssginRole() {
		String originRoleIds = StringUtil.trimToEmpty(request.getParameter("origin_role_ids"));
		String changeRoleIds = StringUtil.trimToEmpty(request.getParameter("change_role_ids"));
		Long aid =  Long.valueOf(StringUtil.trimToEmpty(request.getParameter("aid")));
		accountRBACService.assginAccountRole(originRoleIds, changeRoleIds, aid);
		request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "成功分配角色");
		return SUCCESS;
	}
	
	/**
	 * 修改用户角色权限
	 */
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_ADDORUPDATEROLEPERM,
    		message=MG_ROLE_ADDORUPDATEROLEPERM_MSG)
	public String addOrUpdateRolePerm() {
		Long rid = Long.valueOf(StringUtil.trimToEmpty(request.getParameter("rid")));
		String originPermissionValues = StringUtil.trimToEmpty(request.getParameter("origin_perm"));
		String changePermissionValues = StringUtil.trimToEmpty(request.getParameter("change_perm"));
		System.out.println(request.getParameter("origin_perm"));
		System.out.println(request.getParameter("change_perm"));
		
		accountRBACService.assginRolePermission(originPermissionValues, changePermissionValues, rid);
		
		Role role = accountRBACService.findRoleById(rid);
		//系统角色不给修改
//		if (role.getIsSystem()) {
//		     request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "系统角色不能修改");
//		     return SUCCESS;
//		}
		role.setModifyTime(new Date());
		role.setModifyUser(getSessionPCAaccount());
		request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "成功修改权限");
		return SUCCESS;
	}
	
	/**
	 * 删除角色
	 * @author czw
	 * @return
	 */
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_DELROLES,
    		message=MG_ROLE_DELROLES_MSG)
	public String delRoles() {
	    String ids = request.getParameter("ids");
	    accountRBACService.delRoles(ids);
	    request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "删除角色成功");
	    return SUCCESS;
	}
	
	
	/**
	 * 查看角色权限
	 */
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_VIEWROLEPERM,
    		message=MG_ROLE_VIEWROLEPERM_MSG)
	public String viewRolePerm() {
		Long rid = Long.valueOf(StringUtil.trimToEmpty(request.getParameter("rid")));
		this.role = accountRBACService.findRoleById(rid);
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"url"});
		request.setAttribute
		("menTree", JSONArray.fromObject(accountRBACService.viewPcPermissionTreeOfRole(role.getOrganization().getOid(),rid, true),config).toString());
		return SUCCESS;
	}
	
	/**
	 * 查看所有账号权限
	 */
	@RequiresRoles(value={RBACConstants.PC.CITY_ADMIN_ROLE})
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_VIEWALLPERM,
    		message=MG_ROLE_VIEWALLPERM_MSG)
	public String viewAllPerm() {
	    
	    /*System.out.println(SecurityUtils.getSubject().isPermitted("O_BAR:testAll"));
	    System.out.println(SecurityUtils.getSubject().isPermitted("O_BAR:BIZ_MGE:VIEW"));
	    System.out.println(SecurityUtils.getSubject().isPermitted("O_BAR:BIZ_MG1551E:VIEW"));
	    System.out.println(SecurityUtils.getSubject().isPermitted("O_BAR:BIZ_MGE:sdfdsfds"));
	    System.out.println(SecurityUtils.getSubject().isPermitted("sdfsdfdsf"));*/
	    
	    JsonConfig config = new JsonConfig();
	    config.setExcludes(new String[]{"url"});
	    request.setAttribute
	    ("menTree", JSONArray.fromObject(accountRBACService.getPcPermissionTree(true),config).toString());
	    return SUCCESS;
	}
	
	/**
	 * 修改操作权限名称
	 */
	@RequiresRoles(value={RBACConstants.PC.CITY_ADMIN_ROLE})
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE + MG_ROLE,
    		operateTypeName=MG_ROLE_UPDATEOAUTH,
    		message=MG_ROLE_UPDATEOAUTH_MSG)
	public String updateOAuth() {
	    if (oauth == null || oauth.getOauthId() == null || StringUtil.isBlank(oauth.getOauthName())) 
	        return null;
	    OperateAuth nOAuth = accountRBACService.findOAuthById(oauth.getOauthId());
	    String oauthName = oauth.getOauthName();
	    String oauthCode = nOAuth.getOauthCode();
	    
	    String regex = "^(.*)\\[(.*)\\]$";
	    Map<String, String> map = StringUtil.getMatchStrMap(regex, oauthName);
	    if (map != null) {
	        oauthName = map.get("1");
	        oauthCode = map.get("2");
	    } 
	    try {
    	    nOAuth.setOauthCode(oauthCode);
    	    nOAuth.setOauthName(oauthName);
    	    nOAuth.setOauthDesc(oauthName);
    	    Permission perm = accountRBACService.getPermByOauthId(nOAuth.getOauthId());
    	    perm.setDescription(oauthName);
    	    perm.setPermissionCode(oauthCode);
    	    perm.setPermissionName(oauthName);
    	    accountRBACService.flush(); //让异常马上抛出
	    } catch (Exception e) {
//	        System.out.println(e);
//	        System.out.println(e.getCause());
//	        System.out.println(e.getMessage());
//	        System.out.println(e.getLocalizedMessage());
	        
//	        Caused by: java.sql.BatchUpdateException: ORA-00001: 违反唯一约束条件 (ISM_ACCOUNT.UNIQUE_PERM_NAME)
	        if (e.getCause().getMessage().indexOf("ORA-00001") != -1) {
	            WriteUtil.write(response, "权限编码已经存在:" + oauthCode);
	        } else {
	            WriteUtil.write(response, "修改失败");
	        }
	        return null;
	    }
	    WriteUtil.write(response, "ok");

        return null;
	}
	
	
	/**
	 * 查看组织列表
	 */
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_FINGALLORG,
    		message=MG_ROLE_FINGALLORG_MSG)
	public String fingAllOrg() {
        request.setAttribute("orgTree", JSONArray.fromObject(organizationService.getOrgTreeByOid(getSessionOrgId()),new JsonConfig()).toString());
	    return SUCCESS;
	}
	
	
	/**
	 * goto组织授权
	 */
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_GOTOPERMORG,
    		message=MG_ROLE_GOTOPERMORG_MSG)
	public String goToPermOrg() {
	    request.setAttribute("orgTree", JSONArray.fromObject
	            (organizationService.getOrgTreeByOid(getSessionOrgId()),new JsonConfig())
	            .toString());
	    request.setAttribute("oid", request.getParameter("oid"));
	    return SUCCESS;
	}

	/**
	 * 修改组织授权
	 */
//	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_ADDORUPDATEORGPERM,
    		message=MG_ROLE_ADDORUPDATEORGPERM_MSG)
	public String addOrUpdateOrgPerm() {
	    String oid = request.getParameter("oid");
	    request.setAttribute("oid", oid);
	    String originPermissionValues = StringUtil.trimToEmpty(request.getParameter("origin_perm"));
        String changePermissionValues = StringUtil.trimToEmpty(request.getParameter("change_perm"));
        System.out.println(request.getParameter("origin_perm"));
        System.out.println(request.getParameter("change_perm"));
        accountRBACService.updatePcOrgPermissions(oid, originPermissionValues, changePermissionValues);
	    request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "成功修改组织权限");
	    return SUCCESS;
	}

	/**
     * 检测角色名是否可用  true:可用  false：重复不可用 
     */
    @Transactional()
    public String isValidRoleName() {
        String roleName = StringUtil.trimToEmpty(role.getRoleName());
        Role checkName = accountRBACService.findRoleByName(roleName);
        if (checkName != null) {
            WriteUtil.write(response, "false");
        } else {
            WriteUtil.write(response, "true");
        }

        return null;
    }
	
	
	/**
	 * ajax 调用组织授权树
	 */
	@Transactional
	@OperateLogAnnotation(
    		moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ROLE,
    		operateTypeName=MG_ROLE_GETPERMTREEOFORG,
    		message=MG_ROLE_GETPERMTREEOFORG_MSG)
	public String getPermTreeOfOrg() {
        String oid = request.getParameter("oid");
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"url"});
        try {
            this.writeJSONArray(accountRBACService.getPcPermissionTreeOfOrg(oid, true, true, true), config);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e);
            throw new RuntimeException("组织编码oid: " + oid + "getPermTreeOfOrg fail : " + e);
        }

        return null;
	}
	
    public void setOrganizationService(OrganizationService organizationService) {
        this.organizationService = organizationService;
    }
    public void setAccountRBACService(RBACService accountRBACService) {
        this.accountRBACService = accountRBACService;
    }
    public Role getRole() {
        return role;
    }
    public void setRole(Role role) {
        this.role = role;
    }

    public OperateAuth getOauth() {
        return oauth;
    }

    public void setOauth(OperateAuth oauth) {
        this.oauth = oauth;
    }
    
}
